//
//  LiveStreamListViewController.swift
//  live
//
//  Created by melvyn on 2018/8/17.
//  Copyright © 2018 NEET. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa
import RxDataSources
import Link
import MJRefresh

class LiveStreamListViewController: UIViewController {
    
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
    
    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var openLiveButton: UIButton!
    
    var dataSource:RxCollectionViewEmptyEmbeddedReloadDataSource<LiveTable>! {
        let cellMaker: (CollectionViewSectionedDataSource<LiveTable>, UICollectionView, IndexPath, LiveStreamViewModel)
            -> UICollectionViewCell = { _, view, indexPath, viewModel in
                let cell = view.dequeueReusableCell(
                    withReuseIdentifier: String(describing: LiveStreamCollectionViewCell.self),
                    for: indexPath) as! LiveStreamCollectionViewCell
                cell.viewModel = viewModel
                return cell
        }
        
        return .init(configureCell: cellMaker)
    }
    
    var viewModel: LiveStreamListViewModel = LiveStreamListViewModel()
    
    #if !IB_ENABLED
    override func loadView() {
        let view = LiveStreamListView.init(frame: .zero)
        collectionView = view.collectionView
        openLiveButton = view.openLiveButton
    }
    #endif
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let collectionViewLayout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
        
        let width = (UIScreen.main.bounds.width - 30) / 2
        collectionViewLayout.itemSize = CGSize.init(width: width, height: width * 9 / 16 + 47)
        
        collectionView.emptyDataSetSource = self
        collectionView.emptyDataSetDelegate = self
        
        viewModel.title
            .drive(navigationItem.rx.title)
            .disposed(by: disposeBag)
        
        viewModel.sections
            .drive(collectionView.rx.items(dataSource: dataSource))
            .disposed(by: disposeBag)
        
        Observable.merge(
            viewWillAppear.map { false },
            viewWillDisappear.map { true }
            )
            .filter({ _ in AppManager.default.API.base.isLoggedIn })
            .bind(to: navigationController!.rx.isNavigationBarHidden)
            .disposed(by: disposeBag)
        
        openLiveButton.rx.tap
            .filter { !AppManager.default.API.base.isLoggedIn }
            .flatMapLatest({ Link.shared.rx.performBasicAuthLogin() })
            .subscribe(onNext: { [unowned self] in
                guard $0.isSuccess else {
                    let window = UIApplication.shared.keyWindow!
                    let hud = MBProgressHUD.showAdded(to: window, animated: true)
                    hud.label.text = $0.error?.localizedDescription
                    hud.hide(animated: true, afterDelay: 1)
                    return
                }
                
                self.performSegue(withIdentifier: "me.akii.segue.openLive", sender: nil)
            })
            .disposed(by: disposeBag)
        
        collectionView.mj_header = BLinkRefreshHeader()
        
        collectionView.mj_header
            .rx.event
            .bind(to: viewModel.refresh)
            .disposed(by: disposeBag)
        
        viewModel.isLoading
            .drive(collectionView.mj_header.rx.isAnimating)
            .disposed(by: disposeBag)
    }
    
    #if IB_ENABLED
    override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
        guard identifier == "me.akii.segue.openLive" else {
            return super.shouldPerformSegue(withIdentifier: identifier, sender: sender)
        }
        return AppManager.default.API.base.isLoggedIn
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        guard let destination = segue.destination as? LiveStreamRoomViewController,
            let model = (sender as? LiveStreamCollectionViewCell)?.viewModel?.liveStream.value else {
                super.prepare(for: segue, sender: sender)
                return
        }
        destination.viewModel = LiveStreamRoomViewModel.init(model)
    }
    #endif
    
    public func emptyDataSetShouldDisplay(_ scrollView: UIScrollView!) -> Bool {
        return dataSource.isEmpty
    }
}

extension UIViewController: DZNEmptyDataSetSource {
    
    public func customView(forEmptyDataSet scrollView: UIScrollView!) -> UIView! {
        var configuration = BLinkEmptyConfiguration.default
        
        var animationImages: [UIImage] = []
        for i in 1..<5 {
            animationImages.append(UIImage(named: "livebase_common_loading_error_\(i)_400x400_")!)
        }
        //
        //        for i in 1..<3 {
        //            animationImages.append(UIImage(named: "livebase_common_loading_loading_\(i)_400x400_")!)
        //        }
        //        configuration.animationImages = animationImages
        configuration.size = CGSize(width: 200, height: 250)
        return BLinkEmptyView.init(configuration: configuration)
    }
    
    public func verticalOffset(forEmptyDataSet scrollView: UIScrollView!) -> CGFloat {
        return -view.bounds.height * 0.15
    }
}

extension UIViewController: DZNEmptyDataSetDelegate {
    public func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView!) -> Bool {
        return true
    }
}
